package com.wdf.kotlinlearn.ui

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.wdf.kotlinlearn.bean.LoadState
import com.wdf.kotlinlearn.launch
import com.wdf.kotlinlearn.network.NetworkService
import kotlinx.coroutines.async

/**
 * Function:
 * Author: wonderful on 2019/12/20 17:51
 */
class MainViewModel : ViewModel() {
    // 存放三张图片的url数据
    val imageData = MutableLiveData<List<String>>()
    // 存放网路加载状态信息
    val loadState = MutableLiveData<LoadState>()

    // 从网络加载数据
    /*fun getData() {
        viewModelScope.launch(CoroutineExceptionHandler { _, throwable ->
            // 加载失败
            loadState.value = LoadState.Fail(throwable.message ?: "加载失败")
        }){
            // 更新加载状态
            loadState.value = LoadState.Loading()

            // 并发请求图片数据
            val data1 = async { NetworkService.apiService.getImage() }
            val data2 = async { NetworkService.apiService.getImage() }
            val data3 = async { NetworkService.apiService.getImage() }
            // 通过 LiveData 设置新的值来触发更新UI
            imageData.value = listOf(data1.await(), data2.await(), data3.await()).map {
                it.imgurl
            }

            // 更新加载状态
            loadState.value = LoadState.Success()
        }
    }*/

    fun getData() {
        launch({
            loadState.value = LoadState.Loading()
            val data1 = async { NetworkService.apiService.getImage() }
            val data2 = async { NetworkService.apiService.getImage() }
            val data3 = async { NetworkService.apiService.getImage() }
            imageData.value = listOf(data1.await(), data2.await(), data3.await()).map {
                it.imgurl
            }
            loadState.value = LoadState.Success()
        }, {
            loadState.value = LoadState.Fail(it.message ?: "加载失败")
            Log.e("加载失败", it.message + "")
        })
    }
}